package dbtools;

import java.lang.reflect.Field;

import dbtools.structures.DBField;
import dbtools.structures.DBTable;
import dbtools.structures.DBUniqueKey;

public class DBFactory {
	
	public static <T extends DBTable> T createInstance(Class<T> type) {
		try {
			T tableInstance = type.newInstance();
			initTable(tableInstance);
			return tableInstance;
		} catch (Exception e) {
			throw new Error(e);
		}
	}
	
	public static void initTable(DBTable table){
		for (Field f : table.getClass().getDeclaredFields()){
			try {
				if (DBField.class.isAssignableFrom(f.getType())){
					DBField fld = (DBField) f.get(table);
					fld._setName(f.getName());
					fld._setTable(table);
					table.addField(fld);
				}else if (DBUniqueKey.class.isAssignableFrom(f.getType())){
					DBUniqueKey key = (DBUniqueKey) f.get(table);
					key.setTable(table);
					table.addKey(key);
				}
			} catch (IllegalArgumentException e) {
				throw new Error(e);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			
		}
	}
}
